﻿using System.Threading;
using MonoDevelop.Components.Commands;
using theeg.DependencyAnalysis.CommonAddin.Models;

namespace theeg.DependencyAnalysis.MonoAddin
{
    public class OpenToolWindowHandler : CommandHandler
    {
        private static bool _isOpen;
        private static readonly object LockSingleWindow = new object();

        protected override void Run()
        {
            base.Run();
            Thread thread = new Thread(() =>
            {
                lock (LockSingleWindow)
                {
                    if (_isOpen)
                    {
                        return;
                    }
                    _isOpen = true;
                }
                try
                {
                    var addinWindow = new AddinWindow();
                    var solution = new MonoSolution();
                    solution.Refresh();
                    addinWindow.DataContext = new AddinModel(solution);
                    addinWindow.ShowDialog();
                }
                finally
                {
                    _isOpen = false;
                }
            });
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
        }

        protected override void Update(CommandInfo info)
        {
            base.Update(info);
            info.Enabled = !_isOpen;
        }
    }
}
